package bookManage.Controller.servlet;

import bookManage.Model.service.ServiceImpl;
import bookManage.utils.DBUtil;
import bookManage.utils.JsonUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

/**
 * @BelongsProject: library-management-system-master
 * @BelongsPackage: bookManage.Controller
 * @Author: yuan wang
 * @CreateTime: 2023-02-02  20:43
 * @Description: 展示每本书籍书籍的Servlet，并且是不重名的书籍
 * @Version: 1.0
 */
@WebServlet(name = "BookShow", value = "/manager/BookShow")
public class BookShow extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String jsonString = String.valueOf(JsonUtil.getJson(req));
        JSONObject jsonObject = JSON.parseObject(jsonString);

        ServiceImpl service = new ServiceImpl();

        //传入选择，建议传入选择有"所有"(或者空字符串，即展示所有书籍)，"在馆"展示在馆书籍，"借出"展示借出书籍，"逾期"展示逾期未归还书籍
        String choice = jsonObject.getString("choice");

        PrintWriter out = resp.getWriter();
        JSONObject object = new JSONObject();

        try {
            List<bookManage.Model.entity.BookShow> bookShowList = service.queryBook(choice);
            if (bookShowList != null && bookShowList.size() > 0) {
                object.put("code", "200");
                jsonString = JSONObject.toJSONString(bookShowList);
                object.put("bookList", jsonString);
                out.println(object);
            } else {
                object.put("code", "-1");
                object.put("message", "没有" + choice + "书籍");
                out.println(object);
            }
        } catch (SQLException e) {
            object.put("code", "-1");
            object.put("message", "查询失败");
            out.println(object);
        } finally {
            try {
                DBUtil.freeConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        doGet(req, resp);
    }
}
